<?php
/**
* Load statistic data about transaction Credits
*
* @author       Fabrice Douteaud <clearbudget@douteaud.com>
* @package      actions
* @access       public
*/

/***********************************************************************

  Copyright (C) 2008  Fabrice douteaud (clearbudget@douteaud.com)

    This file is part of ClearBudget.

    ClearBudget is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ClearBudget is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ClearBudget.  If not, see <http://www.gnu.org/licenses/>.


************************************************************************/
//prevent direct access
if(!defined('ENGINEON')) die('Direct access forbidden');

global $context;
$db = class_db::getInstance();

// by default, there is an error
$return['error'] = true;
$return['msg'] = $keys->error_ImproperCall;

// a flag to warn us if date is wrong
$invalidDateFormat = false;
 
// get today's date
$today = date("Y-m-d");

// get the user input and do some checking
$trnCategory = $context->trnCategory;
// if category is unknown, we default to 1 as this is uncategorized
if(!$trnCategory || $trnCategory == null || strtolower($trnCategory)=='null' ) $trnCategory = 1;
$trnDate = formatManualDate($context->trnDate, $invalidDateFormat);
$trnAmount = cleanAmount($context->trnAmount);
$trnComment = clean($context->trnComment);
$trnMemo = clean($context->trnMemo);
$trnDebit = clean($context->trnDebit);
$magic = md5($trnDate.$trnAmount.$trnComment);

// check if date was given
if($context->trnDate == false || $context->trnDate == 'null') {
  $return['error'] = true;
  $return['msg'] = $keys->error_ImproperDate;
  return;
  }
  
// check for invalid date
if($invalidDateFormat) {
  $return['error'] = true;
  $return['msg'] = $keys->error_ImproperDate.' ('.$trnDate.')';
  return;
  }

// check for an amount
if($trnAmount == false ) {
  $return['error'] = true;
  $return['msg'] = $keys->error_ImproperAmount;
  return;
  }

// check for an amount
if($trnComment == false ) {
  $return['error'] = true;
  $return['msg'] = $keys->error_ImproperAmount;
  return;
  }

// get the import ID if there is one already for today
$db->addFields('id');
$db->addFields('importCount');
$db->addWhere('importDate', '=', $today);
$db->addWhere('importType', '=', IMPORTMANUAL);
$db->select('t_imports');
$importData = $db->fetchRow();
if(is_array($importData)) {
  $importId = $importData['id'];
  $insertCounter = $importData['importCount'];
  class_debug::addMsg(__FILE__, 'importId for '.$today.' is '.$importId, DEBUGDEBUG);
  }
else {
  $insertCounter = 0;
  }

// if no insert ID, then we create a new one
if($importData == false) {
  class_debug::addMsg(__FILE__, 'Creating new import for '.$today, DEBUGDEBUG);
  $db->addFields('originalFileName', '');
  $db->addFields('importDate', $today);
  $db->addFields('importType', IMPORTMANUAL);
  $importId = $db->insert('t_imports');
  $newImport = true;
  class_debug::addMsg(__FILE__, 'new importId is '.$importId, DEBUGDEBUG);
  }
else {
  $newImport = false;
  }
  
// tries to insert now
$db->addFields('category', $trnCategory);
$db->addFields('operationDate', $trnDate);
$db->addFields('amount', $trnAmount);
$db->addFields('payee', $trnComment);
$db->addFields('memo', $trnMemo);
$db->addFields('debit', $trnDebit);
$db->addFields('importId', $importId);
$db->addFields('createDate', $today);
$db->addFields('checksum', $magic);
$db->addFields('cleared', '*');
if($db->insert('t_items') !== false) {
  // increment the counter
  $insertCounter++;
  // build the return message
  $return['msg'] = '1 '.$keys->text_importedTransactions;
  $return['msg'] .= ' ('.class_propertyKey::getCurrencySymbol().' '.$trnAmount.' - '.$trnComment.' - '.$trnDate.')';
  $return['error'] = false;
  class_debug::addMsg(__FILE__, 'inserted new transaction', DEBUGDEBUG);
  // we update the import counter
  $db->addFields('importCount', $insertCounter);
  $db->addFields('importDuplicate', '0');
  $db->addWhere('id', '=', $importId);
  $db->update('t_imports');
  class_debug::addMsg(__FILE__, 'imports table update with one more inserts ('.$insertCounter.')', DEBUGDEBUG);
  // let's update the time range if that has changed from the new data
  $report = class_report::getInstance();
  $report->setLimitMonth($context->range, true);
  }
else {
  // build the return message
  $return['msg'] = $keys->text_duplicatedRecords;
  $return['error'] = true;
  class_debug::addMsg(__FILE__, 'Transaction already exists', DEBUGDEBUG);
  // we need to delete the import ID if that was a newly created one
  if($newImport) {
    $db->addWhere('id', '=', $importId);
    $db->delete('t_imports');
    class_debug::addMsg(__FILE__, 'deleting import '.$importId, DEBUGDEBUG);
    }
  }
?>